/* Console.cpp
Copyright (c) 2008 Michael Zahniser
Please note the license terms (MIT license) at the end of this document.

Function definitions for the Console class.
*/

#include "Console.h"

#include "curses.h"



// The constructor starts ncurses.
Console::Console()
	: viewProperties(textMeasure)
{
	initscr();
	raw();
	keypad(stdscr, true);
	noecho();

	// Get the view dimensions.
    getmaxyx(stdscr, viewProperties.lineCount, viewProperties.lineWidth);
	// But, allow one row on the top for the status display.
	--viewProperties.lineCount;
	
	// Initialize the editor pointer to nothing: no file is open.
	// TODO: Open a scratch buffer or something, by default?
	// It could be an unnamed buffer (empty string name), for example.
	editor = editors.end();
}



// The destructor ends ncurses and restores the terminal to normal.
Console::~Console()
{
	while(!editors.empty())
	{
		editors.back()->Save();
		delete editors.back();
		editors.pop_back();
	}
	
	endwin();
}



// Open the given file for editing.
// If another file is open, the file will be opened on a "stack"
// with the previous file still open underneath it. This is how
// browsing history is implemented, and allows the full scroll
// state of each file to be saved when visiting a new one.
// If we already have a copy of the file open, just move that
// copy's editor to the top of the list.
void Console::Edit(const string &fileName)
{
	if(fileName.empty())
		return;
	
	string filePath = fileName;
	if(editor != editors.end())
	{
		// Get the current file's working directory.
		size_t dirPos = (**editor).FileName().rfind('/');
		if(dirPos == string::npos)
			dirPos = 0;
		string rootDir = "/" + (**editor).FileName().substr(0, dirPos);
		while(true)
		{
			if(filePath.size() >= 3 && filePath.substr(0, 3) == "../")
			{
				rootDir = rootDir.substr(0, rootDir.rfind('/'));
				filePath = filePath.substr(3, string::npos);
			}
			else if(filePath.size() >= 2 && filePath.substr(0, 2) == "./")
				filePath = filePath.substr(2, string::npos);
			else if(filePath.size() >= 1 && filePath.substr(0, 1) == "/")
			{
				filePath = filePath.substr(1, string::npos);
				rootDir = "/";
				break;
			}
			else
				break;
		}
		if(rootDir.size() > 1)
			filePath = rootDir.substr(1, string::npos) + "/" + fileName;
	}
	
	// Check whether we are already editing this file.
	list<Editor *>::iterator it = editors.begin();
	for( ; it != editors.end() && (**it).FileName() != filePath; ++it) {}
	
	if(it == editors.end())
	{
		// We are not editing the file yet. Create a new editor for it.
		editors.push_back(new Editor(viewProperties));
		editors.back()->Open(filePath);
	}
	else
	{
		// We are already editing the file. Move its editor to the top.
		editors.splice(editors.end(), editors, it);
	}
	
	editor = editors.end();
	--editor;
}



// Run the event loop.
void Console::Run()
{
	while(!editors.empty())
	{
		Draw();
		int key = getch();
		
		// Quit on ^C or ^Q or ^X.
		if(key == 3 || key == 17 || key == 24)
			break;
		else if(key == 2)
		{
			// Back (^B).
			if(editor != editors.begin())
				--editor;
		}
		else if(key == 6)
		{
			// Foreward (^F).
			++editor;
			if(editor == editors.end())
				--editor;
		}
		else if(key == '`')
		{
			const string &link = (**editor).LinkText();
			if(!link.empty())
			{
				// Split the link into file and anchor.
				size_t pos = link.find("#");
				if(pos == string::npos)
					pos = link.find("::");
				if(pos == string::npos)
					Edit(link);
				else
				{
					// The file name is everything preceding the "#".
					Edit(link.substr(0, pos));
					// The anchor name is the remaining text.
					(**editor).GoToAnchor(link.substr(pos + 1 + (link[pos] == ':'), string::npos));
				}
			}
		}
		else
			(**editor).HandleKey(key);
	}
}



// Update the view.
void Console::Draw() const
{
	// Draw the title bar.
	attron(A_REVERSE);
	mvaddstr(0, 0, (**editor).FileName().c_str());
	for(int i = static_cast<int>((**editor).FileName().size()); i < viewProperties.lineWidth; ++i)
		addch(' ');
	attroff(A_REVERSE);
	
	// Draw the text.
	for(int row = 0; row < viewProperties.lineCount; ++row)
	{
		string str((**editor).Line(row), (**editor).Line(row + 1));
		mvaddnstr(row + 1, 0, str.c_str(), str.length());
		clrtoeol();
	}

	int cursorY = (**editor).CursorLine() + 1;
	int cursorX = (**editor).CursorX();
	if(cursorX >= viewProperties.lineWidth)
		cursorX = viewProperties.lineWidth - 1;
	move(cursorY, cursorX);
}



/* Copyright (c) 2008 Michael Zahniser

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE. */

